package com.sl.plugin.step.childflow;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.bazaarvoice.jolt.Chainr;
import com.google.common.collect.Maps;
import com.sl.core.engine.ProcessConfig;
import com.sl.core.engine.ProcessEngine;
import com.sl.core.engine.meta.impl.AbstractProcessCompDescriptor;
import com.sl.core.engine.step.ProcessCompService;
import com.sl.core.engine.step.impl.AbstractProcessComp;
import com.sl.core.utils.JsonUtil;

import java.util.List;
import java.util.Map;

/**
 *
 */
public class ChildFlowComp extends AbstractProcessComp<Map<String, Object>, Object> implements ProcessCompService {

    public ChildFlowComp(AbstractProcessCompDescriptor abstractProcessCompDescriptor) {
        super(abstractProcessCompDescriptor);
    }

    @Override
    public Object input(Map<String, Object> map) {

        ChildFlowCompDescriptor descriptor = getDescriptor();
        ProcessConfig processConfig = descriptor.getProcessConfig();
        if (ObjectUtil.isNull(processConfig)) {
            return map;
        }
        Object param = map;
        String jolt = this.meta.getStrAttr("jolt");
        if (StrUtil.isNotBlank(jolt)) {
            //未配置映射关系，直接返回null
            List chainrSpecJSON = JsonUtil.toList(jolt, Map.class);
            Chainr chainr = Chainr.fromSpec(chainrSpecJSON);
            param = chainr.transform(map);
        }
        processConfig.setTid(getPipeline().getTid());

        //是否异步执行
        Boolean asyncFlag = this.meta.getBoolAttr("config.asyncFlag");
        Map<String,Object> inputMap = Maps.newHashMap();
        String[] variableNames = this.getPipeline().getVariableNames();
        for (String v : variableNames) {
            inputMap.put(v, this.getPipeline().getVariable(v));
        }
        Object execute = ProcessEngine.INSTANCE.execute(param, processConfig, this, asyncFlag,null,inputMap);
        if (BooleanUtil.isTrue(asyncFlag)) {
            return map;
        }
        return execute;
    }

}
